/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.ipo.mm.web.servlets;
import com.docmosis.SystemManager;
import com.docmosis.document.DocumentProcessor;
import com.docmosis.document.ProcessingException;
import com.docmosis.document.converter.ConversionException;
import com.docmosis.document.converter.ConversionFormat;
import com.docmosis.document.converter.ConversionInstruction;
import com.docmosis.document.converter.NoConvertersRunningException;
import com.docmosis.document.converter.pool.ConverterPoolException;
import com.docmosis.template.Document;
import com.docmosis.template.TemplateStoreException;
import com.docmosis.template.population.Cleanable;
import com.docmosis.template.population.DataProvider;
import com.docmosis.template.population.DataProviderBuilder;
import com.docmosis.template.store.DropStoreHelper;
import com.docmosis.template.store.TemplateContext;
import com.docmosis.template.store.TemplateIdentifier;
import com.docmosis.template.store.TemplateStoreFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Properties;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.ipo.mm.ejb.entities.Institution;
import org.ipo.mm.web.util.ConstantManager;
/**
 *
 * @author Administrator
 */
public class GetInstitutionAddresses extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {


        String fileName = "mailPrint.doc";

        response.setContentType(getServletContext().getMimeType("reports.zip"));
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

        ArrayList<Institution> institutions = (ArrayList<Institution>) request.getSession().getAttribute("selectedInstitutionsForPrint");

        ServletOutputStream out = response.getOutputStream(); 
       try{
            SystemManager.initialise();
       }
       catch(Exception ex)
       {
             Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ex);

        }
        DataProvider dp = prepareData(institutions);

        try {
            // load any templates in the current directory into the template store
            prepareTemplates();

            // run a single document render
            runRender(dp, out);



        } catch (Exception e) {
             Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", e);

        } finally {
            out.close();
            // shutdown the system
            SystemManager.release();
            if (dp instanceof Cleanable) {
                ((Cleanable) dp).cleanup();
            }
        }
    }


    public  DataProvider prepareData(ArrayList<Institution> representatives) {

        // load the data from something

        Institution i = new Institution();
        i.setAddress("Adresa 22");
        i.setName("NAziv institucije");

        DataProviderBuilder dpb = new DataProviderBuilder();

        dpb.add("address",i.getAddress());
        dpb.add("name",i.getName());

        return dpb.getDataProvider();

    }

        private  void prepareTemplates()
            throws IOException, ConversionException, ConverterPoolException, TemplateStoreException, NoConvertersRunningException {
        DropStoreHelper storeHelper = new DropStoreHelper(TemplateStoreFactory.getStore());
        //Folder sa templatime
        storeHelper.process(new File("c:/"), false);
        System.out.println("Template(s) loaded into store");
    }
    private  void runRender(DataProvider dp, OutputStream out)
            throws IOException, ConversionException, ConverterPoolException, TemplateStoreException, ProcessingException {
        System.out.println("Performing a test render");
        String templateFileName = "instPost.doc";
        TemplateIdentifier templateId = new TemplateIdentifier(templateFileName,
                new TemplateContext(""));
        ConversionInstruction instruction = new ConversionInstruction();
        instruction.setConversionFormats(new ConversionFormat[]{                    
                    ConversionFormat.FORMAT_WORD});
        instruction.setOutputFileName("mailPrint");
//        FileOutputStream streamTo = new FileOutputStream("reports.zip");
        try {
            long start = System.currentTimeMillis();
            DocumentProcessor.renderDoc(templateId, dp, instruction, out);
            System.out.println("newDocuments.zip generated in " + (System.currentTimeMillis() - start) + " milliseconds (including wait time)");
        } finally {
//            FileUtilities.close(streamTo);
        }
    }
        private String getTemplateFileName(String key) throws FileNotFoundException, IOException{
            return "instTemplate.doc";
    }

   

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
